package com.xc.base.exception;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public RestErrorResponse exceptionHandler(Exception ex) {
        log.error("系统内部错误Exception：{}", ex.getMessage());
        ex.printStackTrace();
        return new RestErrorResponse("系统内部错误:" + ex.getMessage());
    }

    /**
     * 程序主动抛出的异常 基于 BaseException 自定义的异常
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public RestErrorResponse exceptionHandler(CommonException ex) {
        log.error("异常信息CommonException：{}", ex.getMessage());
        return new RestErrorResponse(ex.getMessage());
    }

    //拦截sql异常，过滤出用户名已经存在的异常信息
    @ExceptionHandler
    public RestErrorResponse exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error("异常信息SQLIntegrityConstraintViolationException：{}", ex.getMessage());
        // Duplicate entry 'daxiaa56' for key 'employee.idx_username' 用户名唯一性
        //在这里统一拦截数据sql数据唯一性的错误，然后解析异常，做出提示
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String property = split[2];
            String msg = property + "不存在";
            return new RestErrorResponse(msg);
        } else {
            return new RestErrorResponse("未知异错误：" + ex.getMessage());
        }


    }

    /**
     * 补货 javax.validation 抛出的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public RestErrorResponse exceptionHandler(MethodArgumentNotValidException ex) {
        log.error("异常信息MethodArgumentNotValidException：{}", ex.getBindingResult());
        List<String> errors = new ArrayList<>();
        //收集所有的异常，逗号拼接
        ex.getBindingResult().getFieldErrors().stream().forEach((e->{
            errors.add(e.getDefaultMessage());
        }));
        String errorInfo = StringUtils.join(errors,",");
        return new RestErrorResponse(errorInfo);
    }

}
